package com.sxfq.loansupermarket.backsystem.modular.weixin.controller;

import com.sxfq.loansupermarket.backsystem.common.controller.BaseController;
import com.sxfq.loansupermarket.backsystem.common.node.MenuNode;
import com.sxfq.loansupermarket.backsystem.common.persistence.dao.UserMapper;
import com.sxfq.loansupermarket.backsystem.common.persistence.model.*;
import com.sxfq.loansupermarket.backsystem.core.log.LogManager;
import com.sxfq.loansupermarket.backsystem.core.log.factory.LogTaskFactory;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroKit;
import com.sxfq.loansupermarket.backsystem.core.shiro.ShiroUser;
import com.sxfq.loansupermarket.backsystem.core.support.HttpKit;
import com.sxfq.loansupermarket.backsystem.modular.base.SqlMapper;
import com.sxfq.loansupermarket.backsystem.modular.basicData.service.IGetListService;
import com.sxfq.loansupermarket.backsystem.modular.system.dao.MenuDao;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
@RequestMapping("/weixin")
public class WeixinLoginController extends BaseController {
    @Autowired
    MenuDao menuDao;

    @Autowired
    UserMapper userMapper;

    @Autowired
    IGetListService getListService;

    @Autowired
    private SqlMapper sqlMapper;

    private String PREFIX = "/weixin/";

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model) {
        List<Integer> roleList = ShiroKit.getUser().getRoleList();  //获取菜单列表
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            String tips = "该用户没有角色，无法登陆";
            model.addAttribute("tips", tips);
            return PREFIX + "/login.html";
        }
        List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
        List<MenuNode> titles = MenuNode.buildTitle(menus);
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        model.addAttribute("areaAbbreviation", ShiroKit.getUser().getAreaAbbreviation());
        model.addAttribute("abbreviation", ShiroKit.getUser().getAbbreviation());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        model.addAttribute("deptid", ShiroKit.getUser().getDeptId());
        model.addAttribute("userId", ShiroKit.getUser().getId());
        model.addAttribute("userName", ShiroKit.getUser().getAccount());
        model.addAttribute("avatar", ShiroKit.getUser().getAvatar()); //用户头像wo
        model.addAttribute("passWord", ShiroKit.getSessionAttr("password"));
        model.addAttribute("titles", ShiroKit.getSessionAttr("titles"));
        model.addAttribute("phonePrivileges", ShiroKit.getUser().getPhonePrivileges());  //是否能查看列表电话
        model.addAttribute("phonePrivilegesexp", ShiroKit.getUser().getPhonePrivilegesexp());  //是否能导出列表电话
        ShiroKit.setSessionAttr("titles", titles);
        model.addAttribute("tips", ShiroKit.getSessionAttr("tips"));
        return PREFIX + "index.html";
    }

    /**
     * 跳转到主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String to_index(Model model) {
        if (ShiroKit.getSessionAttr("username") == null || "null".equals(ShiroKit.getSessionAttr("username"))) {
            ShiroKit.getSubject().logout();
            model.addAttribute("tips", "");
            return "/login.html";
        }
        String tips = "";
        String sql = "select t.id as id , t.simplename,t.fullname,t.abbreviation,t.proportional as proportional,t.level_one_audit as levelOneAudit,t.level_two_audit as levelTwoAudit," +
                "t.province,t.lowest_price_bill as lowestPriceBill,t.cities,t.address,t.member_switch as memberSwitch,t.phone,t.auditswitch,t.auditOfDept,t.area_abbreviation as areaAbbreviation,t.version as version," +
                "t.subordinate_abbreviation as subordinateAbbreviation,CONCAT(sttle_accounts_hour,':',sttle_accounts_minute,':',sttle_accounts_second) as sttleAccountsHour " +
                " from dept t where t.simplename= '" + ShiroKit.getUser().getOutpatientName() + "' limit 1";
        Deptinfos dept = sqlMapper.selectOne(sql, Deptinfos.class);
        String sqluser = "select a.id as id,b.simplename as name,b.version as version,a.avatar as avatar,a.is_refund_admin as isRefundAdmin,a.channel_audit_level as channelAuditLevel," + //a.is_refund_admin as isRefundAdmin,
                " a.account as account,c.name as roleName,c.phone_privileges as phonePrivileges,c.phone_privilegesexp as phonePrivilegesexp,a.audit_node as auditNode,a.register_is_ring as registerIsRing,a.dealyes as dealyes" +
                " from user a left join dept b on a.deptId like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                " where a.account='" + ShiroKit.getSessionAttr("username") + "' " +
                "and b.simplename= '" + ShiroKit.getUser().getOutpatientName() + "' limit 1";
        Userinfos user = sqlMapper.selectOne(sqluser, Userinfos.class);
        String getDDIdsql = "select (select id from role where name='医生' ) as id1 ,(select id from role where name='洁牙师' ) as id2," +
                "(select id from user a where a.account='未指定医生') as id3 from dual";
        Test test = sqlMapper.selectOne(getDDIdsql, Test.class);
        if (user != null) {
        } else {
            String sqluser1 = "select a.id as id,b.id as deptid ,b.version as version,b.simplename as name," +
                    " a.channel_audit_level as channelAuditLevel,a.avatar as avatar,a.account as account,c.name as roleName," +
                    "c.phone_privileges as phonePrivileges,c.phone_privilegesexp as phonePrivilegesexp,a.is_refund_admin as isRefundAdmin," +
                    " a.dealyes as dealyes,a.audit_node as auditNode,a.register_is_ring as registerIsRing from user a left join dept b on a.deptId like CONCAT('%',b.id,',','%') left join role c on a.roleid=c.id " +
                    " where a.account='" + ShiroKit.getSessionAttr("username") + "'  and b.simplename like '%总公司%' limit 1";
            Userinfos user1 = sqlMapper.selectOne(sqluser1, Userinfos.class);
            if (user1 != null) {
                if (user1.getName().indexOf("总公司") != -1) {
                    user = user1;
                }
            } else {
                ShiroKit.getSubject().logout();
                tips = "该用户没有权限登陆该诊所";
                model.addAttribute("tips", tips);
                return "/login.html";
            }
        }
        List<Integer> roleList = ShiroKit.getUser().getRoleList();  //获取菜单列表
        if (roleList == null || roleList.size() == 0) {
            ShiroKit.getSubject().logout();
            tips = "该用户没有角色，无法登陆";
            model.addAttribute("tips", tips);
            return "/login.html";
        }
        ShiroKit.getUser().setLowestPriceBill(dept.getLowestPriceBill());
        ShiroKit.getUser().setDeptName(user.getName());
        ShiroKit.getUser().setId(user.getId());
        ShiroKit.getUser().setRoleName(user.getRoleName());
        ShiroKit.getUser().setPhonePrivileges(user.getPhonePrivileges());  //是否能查看列表电话
        ShiroKit.getUser().setPhonePrivilegesexp(user.getPhonePrivilegesexp());  //是否能导出列表电话
        ShiroKit.getUser().setDealyes(user.getDealyes());
        ShiroKit.getUser().setRegisterIsRing(user.getRegisterIsRing());
        ShiroKit.getUser().setAvatar(user.getAvatar());
        ShiroKit.getUser().setIsRefundAdmin(user.getIsRefundAdmin());
        ShiroKit.getUser().setAuditNode(user.getAuditNode());
        ShiroKit.getUser().setChannelAuditLevel(user.getChannelAuditLevel());
        ShiroKit.getUser().setLevelOneAudit(dept.getLevelOneAudit());
        ShiroKit.getUser().setLevelTwoAudit(dept.getLevelTwoAudit());
        ShiroKit.getUser().setVersion(user.getVersion());
        ShiroKit.getUser().setCompanyVersion(dept.getVersion());
        ShiroKit.getUser().setDoctorRoleId(test.getId1());
        ShiroKit.getUser().setDentistRoleId(test.getId2());
        ShiroKit.getUser().setPublicDoctorRoleId(test.getId3());
        ShiroKit.getUser().setFullname(dept.getFullname());
        ShiroKit.getUser().setAreaAbbreviation(dept.getAreaAbbreviation());
        ShiroKit.getUser().setSubordinateAbbreviation(dept.getSubordinateAbbreviation());
        ShiroKit.getUser().setDeptId(dept.getId() + "");
        ShiroKit.getUser().setMemberSwitch(dept.getMemberSwitch());
        ShiroKit.getUser().setProportional(dept.getProportional());
        ShiroKit.getUser().setAbbreviation(dept.getAbbreviation());
        ShiroKit.getUser().setCities(dept.getCities());
        ShiroKit.getUser().setAddress(dept.getAddress());
        ShiroKit.getUser().setPhone(dept.getPhone());
        ShiroKit.getUser().setAuditOfDept(dept.getAuditofdept());
        ShiroKit.getUser().setAuditswitch(dept.getAuditswitch());
        ShiroKit.getUser().setProvince(dept.getProvince());
        ShiroKit.getUser().setSttleAccountsTime(dept.getSttleAccountsHour());
        ShiroKit.getUser().setSttleAccountsHour(dept.getSttleAccountsHour());
        ShiroKit.getUser().setCustomer_info(dept.getAbbreviation() + "customer_info");
        ShiroKit.getUser().setAbbreviation(dept.getAbbreviation());
        ShiroKit.getUser().setVip_level_info(dept.getAreaAbbreviation() + "vip_level_info");
        ShiroKit.getUser().setPay_service_vip(dept.getAreaAbbreviation() + "pay_service_vip");
        ShiroKit.getUser().setPay_service_members(dept.getAreaAbbreviation() + "pay_service_members");
        ShiroKit.getUser().setPay_service_info(dept.getAreaAbbreviation() + "pay_service_info");
        ShiroKit.getUser().setPay_service_grade_info(dept.getAreaAbbreviation() + "pay_service_grade_info");
        ShiroKit.getUser().setCustomer_info(dept.getAbbreviation() + "customer_info");
        ShiroKit.getUser().setDeal_info(dept.getAbbreviation() + "deal_info");
        ShiroKit.getUser().setRecharge_info(dept.getAbbreviation() + "recharge_info");
        ShiroKit.getUser().setTriage_performance(dept.getAbbreviation() + "triage_performance");
        ShiroKit.getUser().setMedicalrecord_info(dept.getAbbreviation() + "medicalrecord_info");
        ShiroKit.setSessionAttr("jysList", null);
        ShiroKit.getUser().setDoctorInfoList(null);
        ShiroKit.getUser().setMedicalUpPermission(null);
        ShiroKit.setSessionAttr("tcList", null);
        ShiroKit.setSessionAttr("nursesList", null);
        model.addAttribute("abbreviation", dept.getAbbreviation());
        model.addAttribute("areaAbbreviation", dept.getAreaAbbreviation());
        model.addAttribute("abbreviation", dept.getAbbreviation());
        model.addAttribute("outpatientName", ShiroKit.getUser().getOutpatientName());
        model.addAttribute("deptid", dept.getId());
        model.addAttribute("userId", user.getId());
        model.addAttribute("userName", user.getAccount());
        model.addAttribute("avatar", user.getAvatar()); //用户头像
        model.addAttribute("passWord", ShiroKit.getSessionAttr("password"));
        model.addAttribute("titles", ShiroKit.getSessionAttr("titles"));
        model.addAttribute("phonePrivileges", user.getPhonePrivileges());  //是否能查看列表电话
        model.addAttribute("phonePrivilegesexp", user.getPhonePrivilegesexp());  //是否能导出列表电话
        tips = "登录成功";
        model.addAttribute("tips", tips);
        ShiroKit.setSessionAttr("tips", tips);
        return "/index.html";
    }

    //得到子集
    @RequestMapping(value = "/getChildrenValue", method = RequestMethod.POST)
    @ResponseBody
    public List<MenuNode> getChildrenValue(String code, HttpServletResponse response) {
        String accounCodeChildlist = ShiroKit.getUser().getAccount() + code + "childrenValueList";
        if (ShiroKit.getSessionAttr(accounCodeChildlist) == null) {
            String sql = "select b.name as name,b.url as url from role a left join relation c on a.id=c.roleid " +
                    " left join menu b on c.menuid=b.id left join user d on find_in_set(a.id,d.roleid) > 0 " +
                    " where d.account='" + ShiroKit.getUser().getAccount() + "' " +
                    " and pcode='" + code + "' and b.ismenu=1 group by b.id order by b.num";
            ShiroKit.setSessionAttr(accounCodeChildlist, sqlMapper.selectList(sql));
            return ShiroKit.getSessionAttr(accounCodeChildlist);
        } else {
            return ShiroKit.getSessionAttr(accounCodeChildlist);
        }
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/loginWx", method = RequestMethod.GET)
    public String loginWx(Model model, HttpServletResponse response) {
        model.addAttribute("tips", "");
        return PREFIX + "/login.html";
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/loginWx", method = RequestMethod.POST)
    public String loginVali(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        ShiroKit.setSessionAttr("tips", "");
        String username = super.getPara("username").trim();
        String password = super.getPara("password").trim();
        String outpatientName = super.getPara("outpatientName").trim();
        Subject currentUser = ShiroKit.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
        List<Map<String, Object>> outpatientManagementList = getListService.outpatientManagementList();
        ShiroKit.setSessionAttr("outpatientManagementList", outpatientManagementList);
        token.setRememberMe(true);
        currentUser.login(token);
        ShiroUser shiroUser = ShiroKit.getUser();
        super.getSession().setAttribute("shiroUser", shiroUser);
        super.getSession().setAttribute("username", shiroUser.getAccount());
        super.getSession().setAttribute("outpatientName", outpatientName);
        LogManager.me().executeLog(LogTaskFactory.loginLog(shiroUser.getId(), HttpKit.getIp()));
        ShiroKit.getSession().setAttribute("sessionFlag", true);
        ShiroKit.setSessionAttr("outpatientName", outpatientName);
        ShiroKit.setSessionAttr("username", username);
        ShiroKit.setSessionAttr("password", password);
        return REDIRECT + PREFIX + "/";
    }

    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logOut() {
        LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), HttpKit.getIp()));
        ShiroKit.getSubject().logout();
        return REDIRECT + PREFIX + "/login";
    }
}